package recolhalixo;

import jadex.bdi.runtime.IMessageEvent;
import jadex.bdi.runtime.Plan;
import jadex.bridge.IComponentIdentifier;
import jadex.bridge.fipa.SFipa;
import jadex.bridge.service.types.cms.CMSComponentDescription;
import jadex.extension.envsupport.environment.ISpaceObject;
import jadex.extension.envsupport.environment.space2d.Grid2D;
import jadex.extension.envsupport.environment.space2d.Space2D;
import jadex.extension.envsupport.math.IVector2;
import jadex.extension.envsupport.math.Vector1Int;

import java.util.HashMap;

public class Broadcaster {
	public static void broadcastGarbage(Plan origin) {
		// Variaveis
		Grid2D env = (Grid2D)origin.getBeliefbase().getBelief("env").getFact();
		Object oid = env.getAvatar(origin.getComponentDescription()).getId();
		ISpaceObject obj = env.getSpaceObject(oid);
		IVector2 pos = (IVector2)obj.getProperty(Space2D.PROPERTY_POSITION);
		String tipoCamiao=(String)env.getSpaceObject(env.getAvatar(origin.getComponentDescription()).getId()).getProperty("type");
		Vector1Int vision=new Vector1Int((Integer)obj.getProperty("vision"));
		// Preparacao da mensagem
		String tipos[]={"lixo","embal","vidro","papel"};
		for (String t:tipos) {
			IMessageEvent me = origin.createMessageEvent("send_msg");
	
			for (ISpaceObject o:env.getSpaceObjectsByType("camiao_"+t)) {
				IComponentIdentifier name=((CMSComponentDescription)o.getProperty("owner")).getName();
				me.getParameterSet(SFipa.RECEIVERS).addValue(name);
			}
			HashMap<IVector2,Integer> cont= new HashMap<IVector2,Integer>();
			for (Object o:env.getNearObjects(pos,vision, "caixote")) {
				ISpaceObject caix=(ISpaceObject) o;
				if (tipoCamiao.equals(caix.getProperty("type"))) {
					BaseConhecimento bc=(BaseConhecimento)origin.getBeliefbase().getBelief("knows").getFact();
					bc.updateDados(
							(IVector2)caix.getProperty("position"),
							new BaseConhecimento.Caixote((int)origin.getClock().getTick(),(Integer)caix.getProperty("quantity"),(Integer)caix.getProperty("capacity"))
						);
					origin.getBeliefbase().getBelief("knows").setFact(bc);
				}
				if (t.equals(caix.getProperty("type"))) {cont.put((IVector2)caix.getProperty("position"), (Integer)caix.getProperty("quantity"));}
			}
			me.getParameter(SFipa.CONTENT).setValue(cont);
			if ((Boolean)origin.getBeliefbase().getBelief("message_system").getFact())
			{origin.sendMessage(me);}
		}
		
	}
}
